const PENDING = 'pending';
const RESOLVE = 'resolved';
const REJECTED = 'rejected';
function MyPromise(fn){
    let self = this;
    this.status = PENDING;
    this.success = undefined;
    this.errmsg = undefined;

    this.resolvecallbacks = [];
    this.rejectedcallback = [];

    function resolve(val){
        setTimeout(() => {
            if(this.status === PENDING){
                self.status = RESOLVE;
                self.success = val;
                this.resolvecallbacks.forEach(callback=>{
                    callback(val);
                })
            }
        }, 0);
        
    }


    function reject(errmsg){
        setTimeout(() => {
            if(this.status === PENDING){
                self.status = REJECTED;
                self.errmsg = errmsg;
                this.rejectedcallback.forEach(callback=>{
                    callback(errmsg);
                })
            }
        }, 0);
    }
    try{
        fn(resolve,reject);
    }catch(e){
        reject(e);
    }
   
}
MyPromise.prototype.then = function(resolve,reject){
    let self = this;
    if(this.status === PENDING){
        this.rejectedcallback.push(reject);
        this.resolvecallbacks.push(resolve);
    }

    if(this.status === RESOLVE){
        resolve(self.success);
    }

    if(this.status === REJECTED){
        reject(self.errmsg);
    }
}


let p = new MyPromise((resolve,reject)=>{
    setTimeout(() => {
        resolve("resolved");
    }, 1000);
})
p.then(data=>{
    console.log(data);
},err=>{
    console.log(err);
})